from PyQt5.QtWidgets import QWidget, QMenu, QAction
from PyQt5.QtGui import QPainter, QColor, QFont, QIcon, QMouseEvent
from PyQt5.QtCore import QDir, QFileInfo, QRect, Qt, pyqtSlot
import qtawesome as qta


class DictView(QWidget):
    def __init__(self):
        super(DictView, self).__init__()
        self.items = []
        self.item_key = 'path'
        self.context_menu = QMenu()
        self.actDetail = QAction('详细信息')
        self.actIcon = QAction('图标')
        self.createContextMenu()

        self.viewType = 'icon_mode'
        self.columnCount = 2
        self.rowCount = 1
        self.selected_item = {}
        self.hover_x = -1
        self.hover_y = -1
        self.hover_rect = QRect()

        self.icon_size = 32
        self.padding = 32
        self.item_padding = 24
        self.text_font = QFont()
        self.font_size = 14
        self.icon_text_spacing = 12

        self.item_width = self.icon_size + self.item_padding * 2
        self.item_height = self.icon_size + self.item_padding * 2 + self.font_size + self.icon_text_spacing

        self.setMouseTracking(True)

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        if self.viewType == 'icon_mode':
            x = self.padding
            y = self.padding
            row = 0
            col = 0
            for item in self.items:
                if item['is_dir']:
                    icon = qta.icon('mdi.folder', color='dodgerblue')
                else:
                    icon = qta.icon('mdi.file-star-outline', color='dodgerblue')

                if self.hasMouseTracking() and col == self.hover_x and row == self.hover_y:
                    print("row={},col={}".format(row, col))
                    qp.fillRect(self.hover_rect, Qt.darkMagenta)

                old_x = x
                old_y = y
                icon.paint(qp, x+self.item_padding, y+self.item_padding, self.icon_size, self.icon_size)
                rect = QRect(old_x, old_y + self.icon_size + self.icon_text_spacing, self.item_width,
                             self.font_size + self.icon_text_spacing)
                qp.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, item['path'])

                x = x + self.item_width
                col = col + 1
                if x > self.width() - self.padding:
                    row = row + 1
                    col = 0
                    y = y + self.item_height
                    x = self.padding
        elif self.viewType == "detail_mode":
            x = 16
            y = 16
            for item in self.items:
                if item['is_dir']:
                    icon = qta.icon('mdi.folder', color='dodgerblue')
                else:
                    icon = qta.icon('mdi.file-star-outline', color='dodgerblue')

                # if self.hasMouseTracking() and col == self.hover_x and row == self.hover_y:
                #     print("row={},col={}".format(row, col))
                #     qp.fillRect(self.hover_rect, Qt.darkMagenta)

                icon.paint(qp, x, y, 16, 16)
                qp.drawText(x+16 + 6, y+12, item['path'])
                y = y + 16 + 4

        qp.end()

    def resizeEvent(self, event):
        w, h = event.size().width(), event.size().height()
        # print("w={0},h={1}".format(w, h))

        self.columnCount = int(w / self.item_width)
        self.rowCount = int(h / self.item_height)

    def mouseMoveEvent(self, event):
        # event = QMouseEvent()
        pos = event.pos()
        self.hover_x = int((pos.x() - self.padding) / self.item_width)
        self.hover_y = int((pos.y() - self.padding) / self.item_height)
        self.hover_rect = QRect(self.padding+self.hover_x*self.item_width-1,
                                self.padding+self.hover_y * self.item_height-1,
                     self.item_width + 2, self.item_height + 2)
        print("hover_x={0},hover_y={1}".format(self.hover_x, self.hover_y))
        # self.setGeometry(self.hover_rect)
        # self.updateGeometry()
        self.update()

    def mousePressEvent(self, event):
        #event = QMouseEvent
        self.selected_item = self.items[self.hover_y * self.columnCount + self.hover_x]
        if event.button() == Qt.RightButton:
            print("selected_item is {}".format(self.selected_item['path']))
            #self.context_menu.move(self.mapToGlobal(event.pos()))
            self.context_menu.popup(self.mapToGlobal(event.pos()))

    def createContextMenu(self):
        self.actDetail.triggered.connect(self.onDetailClicked)
        self.actIcon.triggered.connect(self.onIconClicked)
        self.context_menu.addAction(self.actIcon)
        self.context_menu.addAction(self.actDetail)
        # self.setContextMenuPolicy(Qt.CustomContextMenu)
        # self.customContextMenuRequested.connect(self.showContextMenu)

    def showContextMenu(self, pos):

        self.context_menu.move(self.mapToGlobal(pos))
        self.context_menu.show()

    def addItem(self):
        pass

    def listDir(self, dirpath):
        item = QFileInfo()
        info_list = QDir(dirpath).entryInfoList()
        for item in info_list:
            dict_item = {'path': item.fileName(), 'is_dir': item.isDir()}
            self.items.append(dict_item)

        self.items.sort(key=lambda x: x['is_dir'], reverse=True)
        self.update()

    @pyqtSlot()
    def onDetailClicked(self):
        self.setViewType('detail_mode')

    @pyqtSlot()
    def onIconClicked(self):
        self.setViewType('icon_mode')

    def setViewType(self, view_type):
        self.viewType = view_type
        self.update()
